<script setup name="billconfig">
import {
  GetListAPI,
  DelDataAPI,
  AddDataAPI,
  EditDataAPI,
  GetMenuPermsAPI,
  GetMenuPermAPI,
  GetCodeRuleAPI,
} from "@/api/system/billconfig";
const tabs = ref("检验配置");
const { proxy } = getCurrentInstance();
const {
  sys_handover_method, //交接方式
  item_rank, // 送检阶别
  sys_inspection_type, // 检验类型
  sys_inspection_method, // 送检方式
  sys_control_items, // 管控项目
  sys_material_category, // 物料类别
  sys_ofcode_type,
} = proxy.useDict(
  "sys_handover_method",
  "sys_ofcode_type",
  "item_rank",
  "sys_inspection_type",
  "sys_inspection_method",
  "sys_control_items",
  "sys_material_category"
);

// 表单ref
const FormsRef = ref(null);

// 选中ID
const Ids = ref([]);

// 是否禁用修改按钮
const Single = ref(false);

// 是否禁用删除按钮
const DelDisabled = ref(false);

// 列表数据
const TableData = ref([]);

// 列表总数量
const total = ref(0);

// 列表加载
const loading = ref(false);

// 保存按钮加载
const BtnLoading = ref(false);

// 信息展示状态
const Drawer = ref(false);

// 新增弹窗
const dialogVisible = ref(false);

// 单据选择弹窗
const BillIsShow = ref(false);

// 弹窗 标题
const title = ref("新增");

// 表格表单 数据
const TableForm = ref([]);

// 勾选 表格表单
const formTebls = ref([]);

// 表单ref
const ruleFormRef = ref();

// 编码规则下拉
const docTheRulesOpt = ref([]);

// 按钮枚举
const buttonList = ref([]);

// 列表枚举
const column = ref([
  {
    label: "采购订单号",
    prop: "purchaseOrderNumber",
  },
  {
    label: "实施单号",
    prop: "purchaseNumber",
  },
  {
    label: "单据状态",
    prop: "purchaseDemandStatus",
  },
  {
    label: "采购类型",
    prop: "procurementTypeDict",
  },
  {
    label: "实施单位",
    prop: "implementationDeptName",
  },
  {
    label: "采购人",
    prop: "purchaseUser",
  },
  {
    label: "供应商信息",
    prop: "supplierName",
  },
  {
    label: "物项属性",
    prop: "materialAttributesName",
  },
  {
    label: "计划类型",
    prop: "planType",
  },
  {
    label: "物资类别",
    prop: "categoryName",
  },
  {
    label: "物资编码",
    prop: "uziCode",
  },
  {
    label: "物资名称",
    prop: "uziName",
  },
  {
    label: "物资标记",
    prop: "markersCode",
  },
  {
    label: "规格型号",
    prop: "uziSpec",
  },
  {
    label: "技术参数",
    prop: "argument",
  },
  {
    label: "单位",
    prop: "unitName",
  },
  {
    label: "是否为设备",
    prop: "isEquipment",
  },
  {
    label: "安全需求",
    prop: "securityRequirement",
  },
  {
    label: "是否安全紧急",
    prop: "isSafe",
  },
  {
    label: "安全急需到货时间",
    prop: "safeArrivalTime",
  },

  {
    label: "采购合同",
    prop: "purchaseContractNumber",
  },

  {
    label: "到货时间",
    prop: "arrivalTime",
  },
  {
    label: "预计到货量",
    prop: "expectedArrival",
  },
  {
    label: "实际到货量",
    prop: "actualArrival",
  },

  {
    label: "备注",
    prop: "procureRemake",
  },
  {
    label: "操作",
    prop: "x",
  },
]);

// const anjianList = ref([])
// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  ofCodeType: "",
  ofCodeStr: "",
  ofCodeName: "",
  selectTime: "",
});

// 配置单据
const menuOptions = ref([]);

/**
 * 查询枚举
 */
const SelectList = ref([
  { model: "selectTime", type: "日期范围" },
  {
    label: "配置编码",
    model: "docCode",
    type: "输入框",
    placeholder: "请输入配置编码",
  },
  {
    label: "配置名称",
    model: "docName",
    type: "输入框",
    placeholder: "请输入配置名称",
  },
  // {
  //   label: '配置单据',
  //   model: 'docConfig',
  //   type: '层级下拉',
  //   placeholder: '请输入配置单据名称',
  //   opt: menuOptions
  // }
]);

/**
 * 弹窗表单
 */
// 表单
const ruleForm = reactive({
  docCode: "", // 配置编码
  docName: "", // 配置名称
  docHandoverMethod: "", // 交换方式
  docConfig: "", // 配置单据
  docTheRules: "", // 编码规则
  docExcessMark: "2", // 超收标志 0为超收 1超收
  docHairMark: "2", // 超发标志 0为超收 1超收
  // docInspectionMark: '2', // 送检标志
  docHandoverMark: "2", // 交接标志
});

// 表格表单校验
const rules = reactive({
  docCode: [
    { required: true, message: "请填写配置编码", trigger: "blur" },
    { validator: proxy.noChinese, trigger: "blur" },
  ],
  docName: [{ required: true, message: "请填写配置名称", trigger: "blur" }],
  docConfig: [{ required: true, message: "请填写配置单据", trigger: "blur" }],
  docTheRules: [
    { required: true, message: "请选择编码规则", trigger: "change" },
  ],
});

// 初始化按钮 原因：没有办法做到完全响应 每次事件触发再次执行
const initBtn = () => {
  buttonList.value = [
    { type: "add", hasPermi: "system:billconfig:add" },
    {
      type: "remove",
      disabled: Single.value,
      hasPermi: "system:billconfig:remove",
    },
  ];
};

// 勾选表格表单
const formTeblChange = (row) => {
  formTebls.value = row;
};

// 码段添加
// const addTypeFn = () => {
//   if (tabs.value == '检验配置')
//     ruleForm.docConfigCode.check.push({
//       checkSubmit: null, // 送检阶别
//       checkType: null, // 送检类型
//       checkMode: null // 送检方式
//     })
//   if (tabs.value == '审核配置')
//     ruleForm.docConfigCode.audit.push({
//       auditControl: null, // 管控项目
//       auditTrigger: null, // 触发按键
//       auditMalType: null // 物料类别
//     })
// }

// 删除表格表单
const removeTypeFn = (scope) => {
  let arr = [];
  if (tabs.value == "检验配置") arr = ruleForm.docConfigCode.check;
  if (tabs.value == "审核配置") arr = ruleForm.docConfigCode.audit;

  if (formTebls.value.length > 0) {
    formTebls.value.forEach((item) => {
      const Find = arr.findIndex((itemy) => item.docId == itemy.docId);
      arr.splice(Find, 1);
    });
  } else {
    arr.splice(arr.length - 1, 1);
  }
};

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = (selection) => {
  Ids.value = selection.map((item) => item.docId);
  Single.value = selection.length != 1;
  DelDisabled.value = !selection.length;
  initBtn();
};
handleSelectionChange([]);

// 新增
const add = () => {
  getMenuPerm();
  billList();
  dialogVisible.value = true;
  title.value = "新增";
};

// 修改
const edit = async (val) => {
  proxy.loading("请稍候...");
  try {
    getMenuPerm();
    billList();
    title.value = "修改";
    for (let Key in val) {
      ruleForm[Key] = val[Key];
    }
    ruleForm.docConfig = val.docConfig;
    dialogVisible.value = true;
  } catch {
  } finally {
    proxy.closeLoading();
  }
};

// 查看
const look = async (val) => {
  proxy.loading("请稍候...");
  try {
    getMenuPerm();
    billList();
    title.value = "查看";
    for (let Key in val) {
      ruleForm[Key] = val[Key];
    }
    ruleForm.docConfig = val.docConfig;
    dialogVisible.value = true;
  } catch {
  } finally {
    proxy.closeLoading();
  }
};

// 新增提交
const addSubmit = async () => {
  BtnLoading.value = true;
  try {
    const valid = await ruleFormRef.value.validate();
    if (!valid) return;
    await AddDataAPI(ruleForm);
    proxy.successMsg("新增成功");
    close();
    getList();
  } catch {
  } finally {
    BtnLoading.value = false;
  }
};

// 修改保存
const editSubmit = async () => {
  BtnLoading.value = true;
  try {
    const valid = await ruleFormRef.value.validate();
    if (!valid) return;

    await EditDataAPI(ruleForm);
    proxy.successMsg("修改成功");
    close();
    getList();
  } catch {
  } finally {
    BtnLoading.value = false;
  }
};

// 删除
const del = async (val) => {
  // console.log(Ids.value.length)
  await DelDataAPI(Ids.value.length <= 0 ? val : Ids.value.join(","));
  proxy.successMsg("删除成功");
  getList();
};

// 弹窗结束
const close = () => {
  dialogVisible.value = false;
  for (let KEY in ruleForm) {
    ruleForm[KEY] = "";
  }
  // ruleForm.docConfigCode = {
  //   check: [],
  //   audit: []
  // }
};

const docHandoverMarkChange = (val) => {
  if (val == 1) {
    rules.docHandoverMethod = [
      { required: true, message: "请选择交换方式", trigger: "change" },
    ];
  } else {
    delete rules.docHandoverMethod;
  }
};

// 选择单据
const nodeClick = async (val) => {
  ruleForm.docConfig = val[val.length - 1];
  // getAnjian(val[val.length - 1])
};

// 查询案件下拉列表
// const getAnjian = async id => {
//   const res = await GetMenuPermsAPI(id)
//   anjianList.value = res.data.map(item => ({
//     label: item.menuName,
//     value: item.menuId
//   }))
// }

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await GetListAPI(query);
    total.value = res.total;
    TableData.value = res.rows;
  } catch (err) {
  } finally {
    loading.value = false;
  }
};

// 查询按钮
const selectSubmit = (val) => {
  for (let KEY in val) {
    query[KEY] = val[KEY];
  }
  getList();
};

/** 单据规则 查询列表 */
const billList = async () => {
  const res = await GetCodeRuleAPI();
  docTheRulesOpt.value = res.data;
};

const getMenuPerm = async () => {
  const res = await GetMenuPermAPI();
  menuOptions.value = res.data;
};

getList();
</script>
<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <!-- 按钮组件 -->
      <p-button :list="buttonList" @add="add" @remove="del" />
      <!-- 表格数据 -->
      <p-table
        keyId="purchaseOrderPlacementId"
        :loading="state.loading"
        :data="tableData"
        :column="column"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        :total="state.total"
        @change="handleSelectionChange"
        @pagination="getList"
      >
        <template #columnCell="{ column, record }">
          <p-dictTag
            v-if="column.prop == 'purchaseDemandStatus'"
            :options="purchase_order_placement"
            :value="record.purchaseDemandStatus"
          />
          <div v-if="column.label == '采购类型'">
            {{
              purchase_type.filter(
                (num) => num.value == record.procurementType
              )[0]?.label
            }}
          </div>
          <div v-if="column.label == '计划类型'" v-colorText="record.planType">
            {{ record.planType }}
          </div>
          <div v-if="column.label == '是否超出'" v-colorText="record.exceed">
            {{ record.exceed ? record.exceed : 0 }}%
          </div>
          <div v-if="column.prop == 'x'">
            <p-operate
              :list="[
                {
                  text: '批次到货',
                  type: 'primary',
                  emit: 'bacthArrival',
                  disabled: record.purchaseDemandStatus != 1,
                  hasPermi: 'carryManage:purchase:record',
                  icon: 'FolderChecked',
                },
                {
                  text: '撤回',
                  type: 'primary',
                  emit: 'revocation',
                  disabled: record.purchaseDemandStatus != 5,

                  hasPermi: 'carryManage:purchase:apply',
                  icon: 'Close',
                },
                {
                  icon: 'View',
                  emit: 'examine',
                  disabled:
                    record.purchaseDemandStatus != 4 &&
                    record.purchaseDemandStatus != 6,
                  text: '审核',
                  type: 'warning',
                  hasPermi: 'monthly:carry:eaminem',
                },

                {
                  icon: 'Edit',
                  emit: 'edit',
                  disabled:
                    record.purchaseDemandStatus != 5 &&
                    record.purchaseDemandStatus != 3,

                  text: '修改',
                  type: 'primary',
                  hasPermi: 'carryManage:purchase:edit',
                },

                {
                  icon: 'Search',
                  emit: 'look',
                  disabled: false,
                  text: '查看',
                  type: 'primary',
                  hasPermi: 'carryManage:purchase:query',
                },
              ]"
              @records="records(record.purchaseOrderPlacementId)"
              @edit="editDic(record.purchaseOrderPlacementId)"
              @look="lookDic(record)"
              @revocation="revocation(record.purchaseOrderPlacementId)"
              @bacthArrival="bacthArrivalDic(record.purchaseOrderPlacementId)"
              @examine="eamineDic(record)"
            />
          </div>
        </template>
      </p-table>
      <!-- <el-table
        v-loading="loading"
        stripe
        border
        :data="TableData"
        style="margin-top: 20px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" type="index" width="80"></el-table-column>
        <el-table-column label="配置编码" prop="docCode" width="220" />
        <el-table-column label="配置名称" prop="docName" width="120" />
        <el-table-column label="配置单据" prop="docConfigDict" width="180" />
        <el-table-column label="交接方式" prop="docHandoverMethodDict" width="180" />
        <el-table-column label="编码规则" prop="docTheRules" width="180" />
        <el-table-column label="超收标志" width="auto">
          <template #default="scope">
            <p-switch disabled v-model="scope.row.docExcessMark" />
          </template>
        </el-table-column>
        <el-table-column label="超发标志" width="auto">
          <template #default="scope">
            <p-switch disabled v-model="scope.row.docHairMark" />
          </template>
        </el-table-column>
        <el-table-column label="交接标志" width="auto">
          <template #default="scope">
            <p-switch disabled v-model="scope.row.docHandoverMark" />
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createBy" width="150" />
        <el-table-column label="创建时间" prop="createTime" width="220" />
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <div>
              <p-operate
                hasPermi="'system:billconfig'"
                @edit="edit(scope.row)"
                @remove="del(scope.row.docId)"
                @look="look(scope.row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table> -->
      <!-- <div class="pagination">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="query.pageNum"
          v-model:limit="query.pageSize"
          @pagination="getList"
        />
      </div> -->
    </el-card>
    <!-- 新增弹窗 -->
    <p-dialog
      width="50%"
      v-model="dialogVisible"
      :title="title"
      @ok="title == '新增' ? addSubmit() : editSubmit()"
      @close="close"
    >
      <template #body>
        <el-form
          ref="ruleFormRef"
          :inline="true"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="配置编码" prop="docCode">
            <el-input
              clearable
              v-model="ruleForm.docCode"
              :disabled="title != '新增'"
              placeholder=" 请输入内容"
            />
          </el-form-item>
          <el-form-item label="配置名称" prop="docName">
            <el-input
              v-model="ruleForm.docName"
              :disabled="title == '查看'"
              clearable
              placeholder="请填写配置名称"
            />
          </el-form-item>
          <el-form-item label="配置单据" prop="docConfig">
            <el-cascader
              v-if="title == '新增'"
              v-model="ruleForm.docConfigs"
              :disabled="title == '查看'"
              :show-all-levels="false"
              :options="menuOptions"
              node-key="id"
              :props="{ label: 'label', value: 'id' }"
              @change="nodeClick"
            />
            <el-input v-else v-model="ruleForm.docConfigDict" disabled />
          </el-form-item>
          <el-form-item label="交接方式" prop="docHandoverMethod">
            <p-select
              :disabled="title == '查看'"
              v-model="ruleForm.docHandoverMethod"
              :option="sys_handover_method"
              placeholder="请选择交接方式"
            />
          </el-form-item>
          <el-form-item label="编码规则" prop="docTheRules">
            <!-- <el-select-v2
              v-model="ruleForm.docTheRules"
              :option="docTheRulesOpt"
              placeholder="请选择编码规则"
              clearable
            /> -->

            <p-select
              :disabled="title == '查看'"
              :option="docTheRulesOpt"
              v-model="ruleForm.docTheRules"
              clearable
              placeholder="请选择编码规则"
            />
          </el-form-item>
        </el-form>
        <div class="swBox">
          <div class="switch flex-items-center">
            <div class="flex-items-center">
              <label for="超收标志">超收标志</label>
              <p-switch
                :disabled="title == '查看'"
                v-model="ruleForm.docExcessMark"
              />
            </div>
            <div class="flex-items-center" style="margin-left: 20px">
              <label for="超收标志">交接标志</label>
              <p-switch
                @change="docHandoverMarkChange"
                :disabled="title == '查看'"
                v-model="ruleForm.docHandoverMark"
              />
            </div>
          </div>
          <div class="switch flex-items-center">
            <div class="flex-items-center">
              <label for="超收标志">超发标志</label>
              <p-switch
                :disabled="title == '查看'"
                v-model="ruleForm.docHairMark"
              />
            </div>
          </div>
        </div>
      </template>
    </p-dialog>
  </div>
</template>
<style scoped lang="scss">
.caozuo {
  float: right;
  display: flex;
  margin-bottom: 10px;
  justify-content: space-evenly;
}
.Btn {
  margin-top: 20px;
  display: flex;
  float: right;
}
.switch {
  display: flex;
}
.app-container v-deep .el-form-item__content {
  width: 228px;
}
.Xiaoheforms {
  display: flex;
}
.swBox {
  margin-left: 20px;
  .switch {
    display: flex;
    align-items: center;
    label {
      display: inline-block;
      width: 60px;
    }
  }
}
</style>
